import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UploadFile, UploadFilter, NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { ApplicationService } from 'src/app/core/service/application.service';
import { ApiService } from 'src/app/core/service/api.service';

@Component({
  selector: 'app-upload-depend-check',
  templateUrl: './upload-depend-check.component.html',
  styleUrls: ['./upload-depend-check.component.scss']
})
export class UploadDependCheckComponent implements OnInit {
  @Input() appUuid: string;
  uploadDependCheck: FormGroup;

  uploading = false;

  fileList: UploadFile[] = [];    // 文件列表
  filters: UploadFilter[] = [{    // 过滤文件
    name: 'type',
    fn: (fileList: UploadFile[]) => {
      this.filter(fileList);
      return fileList;
    }
  }];


  beforeUpload = (file: UploadFile): boolean => {
    this.fileList = this.fileList.concat(file);
    return false;
  }

  filter(fileList: UploadFile[]): any {
    // tslint:disable-next-line:no-bitwise
    const filterFiles = fileList.filter(w => ~['application/json'].indexOf(w.type));
    if (filterFiles.length !== filterFiles.length) {
      this.message.error(`包含文件格式不正确，只支持 json 格式`);
      return filterFiles;
    }
    return fileList;
  }

  constructor(
    private modal: NzModalRef,
    private message: NzMessageService,
    private applicationService: ApplicationService,
    private apiService: ApiService,
    fb: FormBuilder
  ) {
    this.uploadDependCheck = fb.group({
      uploadFile: ['', Validators.compose([Validators.required])]
    });
  }

  handleUpload(): void {
    const formData = new FormData();
    formData.append('appUuid', this.appUuid);
    this.fileList.forEach((file: any) => {
      formData.append('file', file);
    });
    this.uploading = true;
    this.fileUpload('/data/application/uploaddependency', formData);

  }

  fileUpload(path: string, formData: FormData) {
    this.apiService.fileUpLoad(path, formData).subscribe((uploadResult) => {
      if (uploadResult.status === 1) {
        this.message.success('上传成功!', {
          nzDuration: 10000
        });
        this.uploading = false;
        this.modal.destroy();
      }
      if (uploadResult.status === 0) {
        this.message.error('上传失败!', {
          nzDuration: 10000
        });
        this.uploading = false;
      }
    });
  }

  destroyModal(): void {
    this.modal.destroy({ data: 'this the result data' });
  }
  
  /**
   * 下载json模板
   * @param filesName 文件名
   * @param type 文件类型
   */
  downloadFile(filesName: string, type: string) {
    this.applicationService.downloadFile().subscribe((data) => {
      const agentFile = new Blob([data], { type: 'application/' + type });
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(agentFile);
      } else {
        const link = document.createElement('a');
        document.body.appendChild(link);
        link.style.visibility = 'hidden';
        link.href = window.URL.createObjectURL(agentFile);
        link.download = filesName + '.' + type;
        link.click();
        document.body.removeChild(link);
      }
    });
  }


  ngOnInit() {
  }

}
